package net.cloudcodex.client.campaign.presenter;

import net.cloudcodex.client.CloudCodexEventBus;
import net.cloudcodex.client.campaign.view.CampaignCreationView;
import net.cloudcodex.client.campaign.view.CampaignCreationViewImpl;
import net.cloudcodex.client.campaign.view.CampaignsView.Message;
import net.cloudcodex.client.util.ClientUtils;
import net.cloudcodex.client.util.rpc.SuccessCallback;
import net.cloudcodex.shared.dto.Result;
import net.cloudcodex.shared.dto.home.CampaignSummaryDTO;
import net.cloudcodex.shared.rpc.CampaignRPCAsync;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;

@Presenter(view = CampaignCreationViewImpl.class)
public class CampaignCreationPresenter extends
		BasePresenter<CampaignCreationView, CloudCodexEventBus> {
	private final Message message;
	private CampaignRPCAsync campaignService;
	private boolean isViewInit = false;
	private boolean isPopupShowing = false;

	@Inject
	public CampaignCreationPresenter(Message pMessage,
			CampaignRPCAsync campaignService) {
		this.message = pMessage;
		this.campaignService = campaignService;
	}

	@Override
	public void bind() {

		this.view.getCreateButton().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				String name = getValue(view.getCampaignName());
				String game = getValue(view.getCampaignGame());
				String icon = getValue(view.getCampaignIcon());
				String description = getValue(view.getCampaignDescription());

				if (name != null) {

					campaignService.createCampaign(name, game, description,
							icon,
							new SuccessCallback<Result<CampaignSummaryDTO>>() {

								@Override
								public void onSuccess(
										Result<CampaignSummaryDTO> result) {
									if (!result.hasErrors()) {
										eventBus.addNewCampaign(result
												.getData());
									}
								}
							});
					view.hidePopup();
					isPopupShowing = false;
				}
			}

			private String getValue(String text) {

				if (!ClientUtils.isBlankOrNull(text)) {
					return text;
				}
				return null;
			}
		});

		this.view.getCancelButton().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				view.hidePopup();
				isPopupShowing = false;
			}
		});

	}

	public void display() {
		if (!isPopupShowing) {
			isPopupShowing = true;
			if (!isViewInit) {
				this.view.initView();
				isViewInit = true;
			}
			this.view.clearView();
			this.view.showPopup();
		}
	}

	public void onCreateNewCampaign(String NickName) {
		this.display();
	}

}
